<template>
  <MySplitPanes>
    <pane>
      <div class="my-flex-column w100 h100">
        <el-card v-show="state.showQuery" class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
          <el-form :inline="true" label-width="auto" @submit.stop.prevent>
            <el-form-item>
              <my-select-input v-model="state.pageInput.dynamicFilter" :filters="state.filters" @search="onQuery" />
            </el-form-item>
            <el-form-item :label="$t('message.label1.l1')">
              <el-select v-model="state.pageInput.filter.stationId" :placeholder="$t('message.label1.l2')" clearable
                style="width: 150px">
                <el-option v-for="item in state.stationTreeData" :key="item.id" :label="item.stationCode"
                  :value="item.id">
                  <span style="float: left">{{ item.stationCode }}</span>
                  <span style="
                              float: right;
                              color: var(--el-text-color-secondary);
                              font-size: 13px;">
                    {{ item.stationName }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <MyDateTimeRange v-model:startDate="state.pageInput.filter.startTime"
                v-model:endDate="state.pageInput.filter.endTime" style="width: 230px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="ele-Search" @click="onQuery"> {{ $t('message.label1.l3') }} </el-button>
              <el-button type="primary" icon="ele-Search" @click="onFilter"> {{ $t('message.label1.l4') }} </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <el-card class="my-fill mt8" shadow="never">
          <div class="my-tools-box mb8 my-flex my-flex-between">

            <div>
              <el-tooltip effect="dark" :content="state.showQuery ? '隐藏查询' : '显示查询'" placement="top">
                <el-button :icon="state.showQuery ? 'ele-ArrowUp' : 'ele-ArrowDown'" circle
                  @click="state.showQuery = !state.showQuery" />
              </el-tooltip>
            </div>
          </div>

          <el-table ref="tableRef" v-loading="state.loading" :data="state.processedData" row-key="id" border stripe
            highlight-current-row>
            <!-- 固定列 -->
            <el-table-column prop="productCode" :label="$t('message.label1.l9')" width="220" fixed
              show-overflow-tooltip />
            <el-table-column prop="stationCode" :label="$t('message.label1.l10')" width="150" show-overflow-tooltip />
            <el-table-column prop="stationName" :label="$t('message.label1.l11')" width="180" show-overflow-tooltip />
            <el-table-column prop="productModelCode" :label="$t('message.label1.l12')" width="120"
              show-overflow-tooltip />
            <el-table-column prop="productModelName" :label="$t('message.label1.l13')" width="150"
              show-overflow-tooltip />

            <!-- 动态参数列 -->
            <el-table-column v-for="param in state.parameterColumns" :key="param" :label="param" :min-width="120"
              show-overflow-tooltip>
              <template #default="{ row }">
                <div class="param-cell">
                  <span class="param-value">{{ row.parameters[param] ?? '-' }}</span>
                  <span v-if="row.units?.[param]" class="param-unit">({{ row.units[param] }})</span>
                </div>
              </template>
            </el-table-column>

            <!-- 状态列 -->
            <el-table-column prop="status" :label="$t('message.label1.l17')" width="100" align="center" fixed="right">
              <template #default="{ row }">
                <el-tag :type="row.status === 'OK' ? 'success' : 'danger'" effect="dark">
                  {{ row.status || 'N/A' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdTime" :label="$t('message.label1.l18')" width="180" fixed="right">
              <template #default="{ row }">
                {{ dayjs(row.createdTime).format('YYYY-MM-DD HH:mm') }}
              </template>
            </el-table-column>
          </el-table>

          <div class="my-flex my-flex-end mt-4">
            <el-pagination v-model:currentPage="state.pageInput.currentPage"
              v-model:page-size="state.pageInput.pageSize" :total="state.total" :page-sizes="[100, 200, 500, 1000]"
              :background="true" layout="total, sizes, prev, pager, next, jumper" @size-change="handlePageSizeChange"
              @current-change="handlePageChange" />
          </div>
        </el-card>

        <MyFilterDialog ref="myFilterDialogRef" :fields="state.filters" @sure="onFilterSure" />
      </div>
    </pane>
  </MySplitPanes>
</template>

<script setup lang="ts" name="work-param-record">
import { ref, reactive, onMounted, getCurrentInstance, watch, defineAsyncComponent } from 'vue'
import { Pane } from 'splitpanes'
import eventBus from '/@/utils/mitt'
import { auth } from '/@/utils/authFunction'
import { ElTable, ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { listToTree } from '/@/utils/tree'
import { WorkParamRecordApi } from '/@/api/industry/WorkParamRecord'
import { WorkStationApi } from '/@/api/industry/WorkStation'
import type {
  PageInputWorkParamRecordGetPageInput,
  WorkStationGetListOutput
} from '/@/api/industry/data-contracts'
const { proxy } = getCurrentInstance() as any
const myFilterDialogRef = ref();
const MySplitPanes = defineAsyncComponent(() => import('/@/components/my-layout/split-panes.vue'))
const MySelectInput = defineAsyncComponent(() => import('/@/components/my-select-input/index.vue'))
const MyFilterDialog = defineAsyncComponent(() => import('/@/components/my-filter/dialog.vue'))
const MyDateTimeRange = defineAsyncComponent(() => import('/@/components/my-datetime-range/index.vue'))

interface ProcessedRecord {
  id: string
  productCode: string
  stationCode: string
  stationName: string
  productModelCode: string
  productModelName: string
  status: string
  createdTime: string
  parameters: Record<string, any>
  units: Record<string, string>
}

const state = reactive({
  loading: false,
  showQuery: true,
  total: 0,
  export: {
    loading: false
  },
  pageInput: {
    currentPage: 1,
    pageSize: 200,
    filter: {
      stationId: null,
      startTime: null,
      endTime: null
    },
    dynamicFilter: {}
  } as PageInputWorkParamRecordGetPageInput,
  stationTreeData: [] as WorkStationGetListOutput[],
  parameterColumns: [] as string[],
  processedData: [] as ProcessedRecord[],
  filters: [
    {
      field: 'productCode',
      operator: 'Contains',
      description: '产品编号',
      componentName: 'el-input',
      defaultSelect: true
    },
    {
      field: 'createdTime',
      operator: 'Between',
      description: '时间范围',
      componentName: 'el-date-picker',
      props: { type: 'datetimerange' }
    }
  ]
})
// 数据获取与处理
const onQuery = async () => {
  if (state.pageInput.filter?.stationId == null) {
    ElMessage.warning("请选择要查看的工站！");
    return
  }
  state.loading = true
  try {
    const res = await new WorkParamRecordApi().getPage(state.pageInput)
    const rawData = res?.data?.list ?? []

    // 数据聚合处理
    const dataMap = new Map<string, ProcessedRecord>()
    const paramColumns = new Set<string>()
    const unitMap = new Map<string, string>()

    rawData.forEach(item => {
      const key = item.productCode!
      if (!dataMap.has(key)) {
        dataMap.set(key, {
          id: item.id!,
          productCode: item.productCode!,
          stationCode: item.stationCode!,
          stationName: item.stationName!,
          productModelCode: item.productModelCode!,
          productModelName: item.productModelName!,
          status: item.status!,
          createdTime: item.createdTime!,
          parameters: {},
          units: {}
        })
      }

      const record = dataMap.get(key)!
      if (item.parameterName) {
        // 处理参数值
        record.parameters[item.parameterName] = item.parameterValue
        // 收集单位信息
        record.units[item.parameterName] = item.unit || ''
        // 收集参数列
        paramColumns.add(item.parameterName)
        // 缓存单位信息（按参数名）
        if (item.unit && !unitMap.has(item.parameterName)) {
          unitMap.set(item.parameterName, item.unit)
        }
      }
    })

    // 统一处理单位显示
    paramColumns.forEach(param => {
      const unit = unitMap.get(param) || ''
      if (unit) {
        state.stationTreeData.forEach(station => {
          station.stationName
        })
      }
    })

    state.parameterColumns = Array.from(paramColumns)
    state.processedData = Array.from(dataMap.values())
    state.total = res?.data?.total ?? 0

  } catch (error) {
    console.error('数据加载失败:', error)
  } finally {
    state.loading = false
  }
}

// 初始化加载工站数据
const loadStations = async () => {
  try {
    const res = await new WorkStationApi().getList({})
    state.stationTreeData = listToTree(res.data || [])
  } catch (error) {
  }
}

// 分页处理
const handlePageSizeChange = (size: number) => {
  state.pageInput.pageSize = size
  state.pageInput.currentPage = 1
  onQuery()
}

const handlePageChange = (page: number) => {
  state.pageInput.currentPage = page
  onQuery()
}

// 初始化
onMounted(async () => {
  await loadStations()
  // await onQuery()
})

// 其他方法保持原有实现...
</script>

<style scoped>
.param-cell {
  display: flex;
  align-items: center;
  gap: 4px;
}

.param-value {
  font-weight: 500;
  color: var(--el-color-primary);
}

.param-unit {
  font-size: 0.8em;
  color: var(--el-text-color-secondary);
}

:deep(.el-table__header) .el-table__cell {
  background-color: #f8f9fa;
  font-weight: 600;
}

:deep(.el-table__row) .el-table__cell {
  transition: background-color 0.3s ease;
}

:deep(.el-table__row:hover) .el-table__cell {
  background-color: #f3f4f6;
}
</style>